package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.joint.base.bean.EnumManage;
import com.joint.base.entity.Comment;
import com.joint.base.entity.Company;
import com.joint.base.entity.Users;
import com.joint.base.service.CommentService;
import com.joint.base.service.CompanyService;
import com.joint.base.service.UsersService;
import com.joint.core.entity.Client;
import com.joint.core.entity.ProBack;
import com.joint.core.service.ClientService;
import com.joint.core.service.ProBackService;
import com.joint.core.service.ProInfoService;
import com.joint.web.action.BaseAdminAction;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * 后台Action类 - 批注信息列表
 * ============================================================================
 * 版权所有 2014 min_xu。
 * ----------------------------------------------------------------------------
 * 
 * @author min_xu
 * 
 * @version 0.1 2014-4-11
 */

@ParentPackage("com")
public class AjaxCommentAction extends BaseAdminAction {
	private static final long serialVersionUID = -5383463207248344967L;
	
	
	
	@Resource
	private UsersService usersService;
	@Resource
	private CompanyService companyService;
	@Resource
	private ClientService clientService;
	@Resource
	private CommentService commentService;
	@Resource
	private ProInfoService proInfoService;
	@Resource
	private ProBackService proBackService;
	
	private Users users;
	private String name;
	private String type;
	private Client client;
	/**
	 * 批注相关
	 * **/
	private Comment comment;
	private String targetId;
	private String toUsersId;
	private String parentId;
	private String targetObject;
	private String text;
	private String clickId;
	
	private String checkText;

	private List<Comment> listComm;

	private List<Map<String,Object>> listmapComm;

    private List<Map<String,Object>> toUserList;

	public String usersList(){
		Company company=usersService.getCompanyByUser();
		pager=new Pager(0);
		pager=usersService.findByPagerAndCompany(pager,null,company,new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
		List<Users> usersList= (List<Users>) (pager.getTotalCount()>0?pager.getList():Lists.newArrayList());
		List<JSONObject> dataRows=new ArrayList<JSONObject>();
		Map<String,Object> rMap;
		for(Users users:usersList){
			rMap=Maps.newHashMap();
			rMap.put("id",users.getId());
			rMap.put("name",users.getName());
			rMap.put("mobile",users.getMobile());
			dataRows.add(JSONObject.fromObject(rMap));
		}
		return  ajaxJson(dataRows.toString());
	}

	//查看评论判断是否是当前登陆人
	public boolean isCurrentUser(String id){
		Users currentUser=usersService.getLoginInfo();
		 if(StringUtils.equals(currentUser.getId(),id)){
			 return true;
		 }else{
			 return false;
		 }
	}

	// 一览
	public String list() {
		Company company = usersService.getCompanyByUser();
		Users users=usersService.getLoginInfo();
		Map<String,Object> rmap=Maps.newHashMap();
		pager=new Pager(0);
//		pager.setOrderBy("createDate");
//		pager.setOrderType(BaseEnum.OrderType.desc);

		if(company == null){
			return "error_timeout";
		}
		//keyId = "3426359a453ce6050145406f76b3003e";
		if (StringUtils.isEmpty(keyId) == true) {
			
		}else{
			rmap.put("targetId",keyId);
			pager=commentService.findByPagerAndLimit(pager,users,company,rmap);
			List<Comment> commentList= (List<Comment>) (pager.getTotalCount()>0?pager.getList():Lists.newArrayList());
			Map<String,Object>  umap=null;
			listmapComm=Lists.newArrayList();
			for(Comment comment:commentList){
				String names="";
				umap=Maps.newHashMap();
				umap.put("id",comment.getId());
				umap.put("createUser",comment.getCreater().getName());
				umap.put("userId",comment.getCreater().getId());
				umap.put("headImage","");
				umap.put("createDate",comment.getCreateDate());
				umap.put("model",comment.getModel());
				umap.put("text",comment.getText());
				if(StringUtils.isNotEmpty(comment.getAtUsers())){
					for(String s:comment.getAtUsers().split(",")){
						users=usersService.get(s);
						names+="@"+users.getName()+",";
					}
				}
				umap.put("atUsers",names.length()>0?names.substring(0,names.length()-1):"");
				listmapComm.add(umap);
			}



//			for(Comment comment1:listComm){
//				//comment1.setCreateDateText(DataUtil.friendly_time(comment1.getCreateDate()));
//				comment1.setFacedText(FaceUtil.getWebFacedText(comment1.getText()));
//			}
		}
		return "list";
	}

	// 
	public String save() {
		//如果是系统管理员则不允许回复，并且系统管理员记录成系统管理员，单纯企业账号不允许回复
		Users creater = usersService.getLoginInfo();
		Company company=usersService.getCompanyByUser();
		Set<Users> usersSet= Sets.newHashSet();
		String content="";
		String atUsers="";
		Map<String,Object> rmap=Maps.newHashMap();
		rmap.put("state", BaseEnum.StateEnum.Enable);
		pager=usersService.findByPagerAndCompany(new Pager(0),null,company,new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
		List<Users> usersList= (List<Users>) (pager.getTotalCount()>0?pager.getList():Lists.newArrayList());
		if (StringUtils.isEmpty(toUsersId)) {
			return ajaxHtmlCallback("400", "获取批注对象新建人失败！", "操作状态");
		}
		if (StringUtils.isEmpty(targetId)) {
			return ajaxHtmlCallback("400", "获取批注对象失败！", "操作状态");
		}
		if (StringUtils.isEmpty(text)) {
			return ajaxHtmlCallback("400", "批注信息不允许为空！", "操作状态");
		}
		if(StringUtils.indexOf(text,"@")==-1){
			content=text;
			switch (targetObject){
                case "com.joint.core.entity.ProInfo":
                    usersSet.add(proInfoService.get(targetId).getChief());
                    usersSet.addAll(proInfoService.get(targetId).getGroup());
                    break;
                case "com.joint.core.entity.ProBack":
                    usersSet.add(proBackService.get(targetId).getProInfo().getChief());
                    usersSet.addAll(proBackService.get(targetId).getProInfo().getGroup());
                    break;
                default:
                    usersSet.addAll(usersList);
            }
		}else{
			LogUtil.info("{ toUsersId }" + toUsersId);
			String[] arr=text.split(" ");
			String s="";
			for(String str:arr){
				if(str.indexOf("@")!=-1){
					s=str;
					s=s.substring(1,str.length());
					rmap.put("name",s);
					rmap.put("state", BaseEnum.StateEnum.Enable);
					rmap.put("company",company);
					pager=usersService.findByPagerAndCompany(new Pager(0),null,company,rmap);
					List<Users> userList= (List<Users>) (pager.getTotalCount()>0?pager.getList():Lists.newArrayList());
					if(userList.size()>0){
						usersSet.add(userList.get(0));
						atUsers+=userList.get(0).getId()+",";
					}
				}else{
					content=str;
				}
			}
		}

		if(StringUtils.isEmpty(content)){
			return ajaxHtmlCallback("400", "批注信息不允许为空！", "操作状态");
		}

		Comment comment = new Comment(creater,targetId,targetObject,null, EnumManage.CommentModelEnum.text,content,atUsers);
		comment.setCompany(creater.getCompany());
		if(usersSet.size()>0){
			commentService.createNewCommentApp(comment, usersSet);
		}

//		if(StringUtils.contains(toUsersId, ",")){
//			LogUtil.info("{ toUsersId in }" + toUsersId);
//			//usersSet.addAll(getUserSpit(toUsersId));
//			Comment comment = new Comment(creater,usersService.get(toUsersId),targetId,targetObject,parent, EnumManage.CommentModelEnum.text,content,null);
//			comment.setCompany(creater.getCompany());
//			//commentService.createNewComment(comment, usersSet);
//		}else{
//			Comment comment=new Comment(creater,usersService.get(toUsersId),targetId,targetObject,parent,EnumManage.CommentModelEnum.text,content,null);
//			comment.setCompany(creater.getCompany());
//			//commentService.createNewComment(comment,usersSet);
//		}


		return ajaxHtmlCallback("200",  "批注成功。","操作状态");
	}
	
	public String feedbackCheck(){
		comment = commentService.get(keyId);
		//comment.setCommentState(CommentState.)
		//comment.setType(CommentTypeEnum.important);
		comment.setIfFeedbackChecked(1);
		comment.setCheckText(checkText);
		commentService.update(comment);
		return ajaxHtmlCallback("200", "需求确认成功。", "");
	}
	//@我的批注列表
	public String toUsersList(){
        users = usersService.getLoginInfo();
        Company company = usersService.getCompanyByUser();
        pager = new Pager();
        rows = LISTVIEW_WEB_SIZE;
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderType(BaseEnum.OrderType.desc);
        pager.setOrderBy("createDate");

        toUserList = Lists.newArrayList();
        List<Comment> comments = Lists.newArrayList();
        //pager = commentService.getPagerRootByToUsers(pager, users);
        Users users = usersService.getLoginInfo();
        Map rmap = Maps.newHashMap();
        rmap.put("toUsers",users);
        pager = commentService.findByPagerAndCompany(pager, null, company, rmap);
        comments = (List<Comment>) pager.getList();


        for(Comment c : comments){
            Map cmap = commentService.getListMap(c);
            Object obj = commentService.getObject(c.getTargetClass(),c.getTargetId());
            if(obj instanceof ProBack){
                ProBack proBack = (ProBack) obj;
                cmap.put("theme",proBack.getProInfo().getName()+"中进行反馈");
            }
            toUserList.add(cmap);
        }
        LogUtil.info("{ toUserList }" + toUserList.size());

		return "toUsersList";
	}
	
	//我批注的列表
	public String createrList(){
		users = usersService.getLoginInfo();
		pager = new Pager();
		pager.setPageNumber(1);// 页码
		pager.setPageSize(100);// 页Size
		pager.setOrderType(BaseEnum.OrderType.desc);
		pager.setOrderBy("createDate");
		pager = commentService.getPager(pager, users, null, null, null, -1, -1, null, null,new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
		
		List<Comment> comments = (List<Comment>) pager.getList();
		listComm = new ArrayList<Comment>();
		for(Comment c : comments){
			if(c.getTargetId() != null){
//				Map<String,String> map = commentService.getTargetMap(c);
//				c.setSubject(map.get("subject"));
//				c.setClientName(map.get("clientName"));
//				c.setUriName(map.get("type"));
//				listComm.add(c);
			}
		}
		return "createrList";
	}

    private Set<Users> getUserSpit(String str){
        Set<Users> usersSet=new HashSet<Users>();
        String[] ary=str.split(",");
        for(String item:ary){
            if(StringUtils.isNotEmpty(item)){
                usersSet.add(usersService.get(item));
            }
        }
        return  usersSet;
    }
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public Users getUsers() {
		return users;
	}

	public void setUsers(Users users) {
		this.users = users;
	}

	public List<Comment> getListComm() {
		return listComm;
	}

	public void setListComm(List<Comment> listComm) {
		this.listComm = listComm;
	}

	public List<Map<String, Object>> getListmapComm() {
		return listmapComm;
	}

	public void setListmapComm(List<Map<String, Object>> listmapComm) {
		this.listmapComm = listmapComm;
	}

	public Comment getComment() {
		return comment;
	}

	public void setComment(Comment comment) {
		this.comment = comment;
	}

	public String getTargetId() {
		return targetId;
	}

	public void setTargetId(String targetId) {
		this.targetId = targetId;
	}

	public String getToUsersId() {
		return toUsersId;
	}

	public void setToUsersId(String toUsersId) {
		this.toUsersId = toUsersId;
	}

	public String getTargetObject() {
		return targetObject;
	}

	public void setTargetObject(String targetObject) {
		this.targetObject = targetObject;
	}

	public String getParentId() {
		return parentId;
	}

	public void setParentId(String parentId) {
		this.parentId = parentId;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public String getClickId() {
		return clickId;
	}

	public void setClickId(String clickId) {
		this.clickId = clickId;
	}

	public String getCheckText() {
		return checkText;
	}

	public void setCheckText(String checkText) {
		this.checkText = checkText;
	}

    public List<Map<String, Object>> getToUserList() {
        return toUserList;
    }

    public void setToUserList(List<Map<String, Object>> toUserList) {
        this.toUserList = toUserList;
    }
}
